package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import bean.Usuario;
import dao.SqlServer;

/**
 * Servlet implementation class CadastrarSe
 */
@WebServlet(name = "ServletCadastrarSe", urlPatterns = { "/ServletCadastrarSe" })
public class CadastrarSe extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SqlServer dao = new SqlServer();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CadastrarSe() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Capturar o Stream enviado pelo Android
		InputStreamReader inputStream = new InputStreamReader( request.getInputStream() ); 
		BufferedReader reader = new BufferedReader( inputStream );
		String entrada = reader.readLine();
		System.out.println(entrada);
		
		//Transformando a leitura da resposta para interpreta��o via JSON
		JSONObject jsonReq = JSONObject.fromObject( entrada  );
		//Capturando o valor enviado
		String usuario, senha;
		
		senha = jsonReq.getString("senha");
		usuario = jsonReq.getString("usuario");
		
		
		JSONObject jsonResp;
		
		boolean autenticado = false;
		
		if(dao.cadastrarUsuario(usuario, senha)){
			autenticado = true;
		}				
		
		HashMap<String,String> dadosRetorno = new HashMap<String,String>();
		dadosRetorno.put( "message", autenticado+"" );
        jsonResp = JSONObject.fromObject( dadosRetorno );
		response.setContentType("application/json");
		
		PrintWriter out = response.getWriter();
		out.print( jsonResp );
		out.flush();
	}

}
